<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/16
 * Time: 13:44
 */

namespace app\admin\service\business\controllers\Access\Rule;


use app\admin\service\business\BaseControllerService;
use app\admin\service\business\controllers\Access\Achieve\Traits\Additional;
use app\admin\service\business\controllers\Access\Rule\Models\AdminRuleModel;

/**
 * Class AdminRuleService
 *
 * @property-read AdminRuleModel $model
 *
 * @package app\admin\service\business\controllers\Access\Rule
 */
class AdminRuleService extends BaseControllerService
{
    use Additional;

    protected $rely = [
        'model' => AdminRuleModel::class
    ];

    /**
     * 查询列表
     *
     * @param array $where
     * @param int $limit
     * @return mixed
     */
    public function resList(array $where, int $limit)
    {
        $list = $this->model->getList($where['key'] ?? [], [], true, $limit);

        foreach ($list as $k => $v) {
            $list[$k]->routes = json_encode(array_reduce(explode("\n", $v->routes), function ($result, $v) {
                array_push($result, htmlspecialchars($v));

                return $result;
            }, []));
        }

        return $list;
    }

    /**
     * 查询单条信息
     *
     * @param int $id
     * @return mixed
     */
    public function resFind(int $id)
    {
        $result = $this->model->getFind($id);

        return $result;
    }

    /**
     * 操作数据
     *
     * @param array $params
     * @param int $id
     * @return array
     */
    public function operating(array $params, int $id = 0): array
    {
        // 判断 name 是否重复
        if ($this->model->isUnique($params['name'], $params['method'], $id)) return echoArr(500, '此请求下已有当前名称');

        // 处理多个请求方式
        $methods = array_filter(explode(',', $params['method']), function ($value) {
            return in_array($value, $this->methods());
        });
        if (!$methods) return echoArr(500, '请选择请求方式');

        // 需操作的数据
        $data = [
            'name' => $params['name'],
            'method' => implode('|', $methods),
            'routes' => trim($params['routes']),
        ];

        try {
            // 执行数据更新
            if ($id) {
                $this->model->edit($data, $id);
            } else {
                $this->model->insert($data);
            }

            return echoArr(200);
        } catch (\Exception $e) {
            return echoArr(800);
        }
    }


    /**
     * 删除数据
     *
     * @param int $id
     * @return array
     */
    public function del(int $id): array
    {
        // 判断权限是否被角色绑定
        if ($this->model->isRoleRule($id)) return echoArr(500, '当前权限已被角色绑定，请先清除角色权限');

        try {
            $this->model->delete($id);

            return echoArr(200, '操作成功');
        } catch (\Exception $e) {
            return echoArr(800);
        }
    }
}
